package com.drore.logapp.base;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.drore.logapp.utils.GlobalConfig;
import com.drore.logapp.utils.ToastUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by xiangl
 * on 2018/4/26 0026 上午 10:30
 * description :
 */
public abstract class BaseActivity<T extends BasePresenterI, V> extends AppCompatActivity implements BaseViewI<V> {
    /**
     * 子类标识
     */
    protected String TAG;
    protected T mPresenter;
    public Context pContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = getClass().getSimpleName();
        setContentView(getLayoutId());
        pContext = this;
        initView();
    }

    /**
     * 加载载布局
     */
    public abstract int getLayoutId();

    /**
     * 初始化view
     */
    protected abstract void initView();

    public void launch(Class clazz) {
        startActivity(new Intent(this, clazz));
    }

    public void launch(Intent intent) {
        startActivity(intent);
    }

    @Override
    public void showDataError(String errorMessage) {
        showToast(errorMessage);
    }


    @Override
    public void showDataSuccess(V datas) {
    }

    /**
     * 获取Presenter
     */

    public T getPresenter() {
        try {
            Object obj = this.getMyClass().newInstance();
            return (T) obj;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unsubcrible();
        }
    }

    /**
     * 左入右出的动画
     */

    //得到泛型类T
    Class getMyClass() {
        System.out.println(this.getClass());
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            Type[] ptype = ((ParameterizedType) type).getActualTypeArguments();
            return (Class) ptype[0];  //将第一个泛型T对应的类返回（这里只有一个）
        } else {
            return Object.class;//若没有给定泛型，则返回Object类
        }

    }

    public void setViewMargin(View view, int left, int top, int right, int bottom) {
        ViewGroup.MarginLayoutParams lp = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        if (lp.leftMargin != left || lp.topMargin != top || lp.rightMargin != right || lp.bottomMargin != bottom) {
            lp.setMargins(left, top, right, bottom);
            view.setLayoutParams(lp);
        }
    }

    public void showToast(String s) {
        ToastUtil.showToast(this, s, Toast.LENGTH_SHORT);
    }


    /************************************************** 6.0以上系统判断权限  --> start ***************************************/

    /**
     * 判断权限
     *
     * @param permission 权限名
     * @param code       请求码
     * @return 是否有权限
     */
    protected boolean checkPermission(String permission, int code) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{permission}, code);
        } else {
            return true;
        }
        return false;
    }

    /**
     * 判断多个权限
     *
     * @param code        请求码
     * @param permissions 多个权限名构成的数组
     * @return 是否有权限
     */
    protected boolean checkPermissionsReturnBoolean(String[] permissions, int code) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, permissions, code);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断多个权限
     *
     * @param code        请求码
     * @param permissions 多个权限名构成的数组
     * @return grantedPermissions 已允许的权限集合
     */
    protected List<String> checkPermissionsReturnList(String[] permissions, int code) {
        List<String> grantedPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, permissions, code);
                return null;
            } else {
                grantedPermissions.add(permission);
            }
        }
        return grantedPermissions;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        List<String> grantedPermissions = new ArrayList<>();//已允许的权限集合
        switch (requestCode) {
            case GlobalConfig.EXTERNAL_STORAGE_CODE://存储卡
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toUseStorage();
                } else {
                    showTipsDialog();
                }
                break;
            case GlobalConfig.PHONE_CODE://打电话
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toUsePhone();
                } else {
                    showTipsDialog();
                }
                break;
            case GlobalConfig.SMS_CODE://发短信
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toUseSMS();
                } else {
                    showTipsDialog();
                }
                break;
            case GlobalConfig.CAMERA_CODE://照相机
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toUseCamera();
                } else {
                    showTipsDialog();
                }
                break;
            case GlobalConfig.LOCATION_CODE://定位
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    toUseLocation();
                } else {
                    showTipsDialog();
                }
                break;
            case GlobalConfig.MULTIPLE_CODE://同时请求多个权限
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults.length > 0 && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        grantedPermissions.add(permissions[i]);
                    } else {
                        showTipsDialog();
                    }
                }
                if (grantedPermissions.size() > 0) {
                    getGrantedPermissionList(grantedPermissions);
                }
                break;
        }
    }

    /**
     * 获取存储卡相关权限后的操作
     */
    protected void toUseStorage() {

    }

    /**
     * 获取电话相关权限后的操作
     */
    protected void toUsePhone() {
    }

    /**
     * 获取短信相关权限后的操作
     */
    protected void toUseSMS() {
    }

    /**
     * 获取照相机相关权限后的操作
     */
    protected void toUseCamera() {
    }

    /**
     * 获取位置相关权限后的操作
     */
    protected void toUseLocation() {

    }

    /**
     * 获取已允许的权限集合，用于判断多个权限才能进行的操作
     */
    protected void getGrantedPermissionList(List<String> grantedPermissions) {
    }

    /**
     * 显示提示对话框
     */
    private void showTipsDialog() {
        new AlertDialog.Builder(this)
                .setTitle("提示信息")
                .setMessage("当前应用缺少必要权限，该功能暂时无法使用。如若需要，请单击【确定】按钮前往设置中心进行权限授权。")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                }).show();
    }

    /**
     * 启动当前应用设置页面
     */
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }
/************************************************** 6.0以上系统判断权限  --> end8***************************************/
}
